package cn.ll.action;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import cn.ll.po.Contract;
import cn.ll.po.CurrencyRate;
import cn.ll.po.Department;
import cn.ll.po.Item;
import cn.ll.po.Permissions;
import cn.ll.po.Task;
import cn.ll.po.User;
import cn.ll.service.ContractService;
import cn.ll.service.CurrencyRateService;
import cn.ll.service.ItemService;
import cn.ll.service.TaskService;
import cn.ll.util.SystermUtil;
import cn.ll.vo.LoginUser;

public class ContractAction extends Action {

	/**
	 * 保存协议单
	 * 
	 * @param request
	 * @param response
	 */
	public void save(HttpServletRequest request, HttpServletResponse response) {
		ContractService contractService = (ContractService) this.getApplicationContext().getBean("contractService");
		CurrencyRateService currencyRateService = (CurrencyRateService) this.getApplicationContext().getBean(
				"currencyRateService");

		String customerid = request.getParameter("customerid");
		String customername = request.getParameter("customername");
		String connector = request.getParameter("contactor");
		// String userName = request.getParameter("user_name");
		String proname = request.getParameter("proname");
		String region = request.getParameter("region");
		String country = request.getParameter("country");
		String city = request.getParameter("city");
		String size = request.getParameter("size");
		String currency = request.getParameter("currency");
		String data_rdy_time = request.getParameter("dataRdyTime");
		String finishTime = request.getParameter("finishTime");
		String signdate = request.getParameter("signdate");
		//String type = request.getParameter("type");
		String cost = request.getParameter("cost");
		String requirements = request.getParameter("requirements");
		String itemlist_str = request.getParameter("itemlist");
		String rootid = request.getParameter("rootid");

		LoginUser loginuser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");
		

		Contract contract = new Contract();
		contract.setCustomerid(customerid);
		contract.setCustomername(customername);
		contract.setConnectername(connector);
		contract.setUserid(loginuser.getUser().getId());
		contract.setUserName(loginuser.getUser().getUsername());
		contract.setProname(proname);
		contract.setRegion(region);
		contract.setCountry(country);
		contract.setCity(city);
		contract.setSize(size);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		try {
			if (data_rdy_time != null && data_rdy_time.length() > 0) {
				Date rdydate = sdf.parse(data_rdy_time);
				contract.setDataRdyTime(rdydate);
			}
			if (finishTime != null && finishTime.length() > 0) {
				Date finidate = sdf.parse(finishTime);
				contract.setFinishTime(finidate);
			}
			if (signdate != null && signdate.length() > 0) {
				Date signDate = sdf.parse(signdate);
				contract.setSigndate(signDate);
			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//设置汇率的转换
		contract.setCurrency(currency);
		CurrencyRate currencyRate = currencyRateService.findByCurrency(currency);
		if (currencyRate != null) {
			float contract_cost = Float.valueOf(cost) * currencyRate.getRate();
			contract.setCostRmb(contract_cost);
		}
		// contract.setDataRdyTime(dataRdyTime)
		if (rootid != null && rootid.length() > 0) {
			contract.setType("1");
			contract.setRootid(rootid);
		} else {
			contract.setType("0");
		}

		contract.setCost(Float.valueOf(cost));
		contract.setRequirements(requirements);
		contract.setCreatetime(new Date());
		contract.setVerifytime(new Date());
		

		Department department = (Department)request.getSession().getAttribute("CURRENT_DEPARTMENT");

		contractService.save(contract,department);
		
		// 添加子项目
		JSONArray jsa = JSONArray.fromObject(itemlist_str);

		ItemService itemService = (ItemService) this.getApplicationContext().getBean("itemService");

		int len = jsa.size();
		for (int i = 0; i < len; i++) {
			JSONObject jso = jsa.getJSONObject(i);
			String itype = jso.getString("type");
			String isubtype = jso.getString("subtype");
			float icost = jso.getInt("cost");
			String icosttype = jso.getString("costtype");
			int iamount = jso.getInt("size");
			float subtotal = (float) jso.getDouble("amount");
			Item item = new Item();
			item.setContractid(contract.getId());
			item.setCreatetime(new Date());
			item.setCreateid(loginuser.getUser().getId());
			item.setType(itype);
			item.setSubtype(isubtype);
			item.setCost(icost);// 设置单
			item.setAmount(iamount);// 设置子项的数量
			item.setSubtotal(subtotal);// 设置子项总额
			item.setTotalCostRmb(subtotal);// 设置人民币总额 *currencyRate.getRate()
			item.setCosttype(icosttype);
			item.setRootid(contract.getRootid());
			itemService.save(item);
		}
		Map rs = new HashMap();
		rs.put("success", true);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 更新协议的状态，接受的数据类型是一个协议id=>状态的列表
	 * 
	 * @param request
	 * @param response
	 */
	public void updateStatus(HttpServletRequest request, HttpServletResponse response) {
		String contract_status_str = request.getParameter("itemlist");
		ContractService contractService = (ContractService) this.getApplicationContext().getBean("contractService");
		JSONArray jsa = JSONArray.fromObject(contract_status_str);
		int len = jsa.size();
		for (int i = 0; i < len; i++) {
			JSONObject jso = jsa.getJSONObject(i);
			String contractid = jso.getString("id");
			int status = jso.getInt("status");
			contractService.updateStatus(contractid, status);
		}
		Map rs = new HashMap();
		rs.put("success", true);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 删除协议,根据ID:先查询出对象,再删除
	 * 
	 * @param request
	 * @param response
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		if (id == null || id.length() > 0) {
			Map rs = new HashMap();
			rs.put("success", false);
			rtn(rs, request, response);
			return;
		}
		ContractService contractService = (ContractService) this.getApplicationContext().getBean("contractService");
		Contract contract = new Contract();
		// contract = contractService.findById(4);
		contract.setId(id);
		// contract.setId(4);
		contractService.delete(contract);
		Map rs = new HashMap();
		rs.put("success", true);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 获取协议列表(分页)
	 * 
	 * @param request
	 * @param response
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public void select(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		ContractService contractService = (ContractService) this.getApplicationContext().getBean("contractService");
		String limit = request.getParameter("limit");
		String start = request.getParameter("start");
		if (limit == null || limit.length() > 0) {
			limit = "10";
		}
		if (start == null || start.length() > 0) {
			start = "1";
		}

		List<Contract> list = null;
		Integer count = 0;// 总记录数量
		// 获得当前登录用户的权限列表
		List<Permissions> curplist = (List<Permissions>) request.getSession().getAttribute("CURRENT_PERMISSIONS");
		// 是否有协议管理者的读权限
		List<Permissions> rp = SystermUtil.usrPermissionsList("contractmgr", "read", curplist);
		if (rp.size() > 0) {
			String scope = "self";
			for (int i = 0; i < rp.size(); i++) {
				Permissions pm = rp.get(i);
				if (pm.getScope().equalsIgnoreCase("all")) {
					scope = pm.getScope();
				}
			}
			if (scope.equalsIgnoreCase("self")) {// 普通的销售,只能查看属于自己的协议
				LoginUser loginUser = (LoginUser) request.getAttribute("CURRENT_USER");
				if (loginUser != null) {
					Map map = contractService.selectSelfContractList(loginUser.getUser().getId(), Integer
							.parseInt(start), Integer.parseInt(limit));
					list = (List<Contract>) map.get("list");
					count = (Integer) map.get("totalcount");
				}
			} else {// 拥有查看所有协议的权限,管理员或者审核人员//
				Map map = contractService.selectAllContractList(Integer.parseInt(start), Integer.parseInt(limit));
				list = (List<Contract>) map.get("list");
				count = (Integer) map.get("totalcount");
			}

		}
		
		List rsls = new ArrayList<Map>();
		for (Contract contract : list) {
			Map mp = BeanUtils.describe(contract);
			if(contract.getStatus() == 0){
				mp.put("statusStr", "待审批");
			}else if(contract.getStatus() == 1){
				mp.put("statusStr", "审核通过");
			}else if(contract.getStatus() == 2){
				mp.put("statusStr", "审核未通过");
			}
			
			if(contract.getType().equals("0")){
				mp.put("typeStr","协议单");
			}else if(contract.getType().equals("1")){
				mp.put("typeStr","修正单");
			}
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			mp.put("dataRdyTime", sdf.format(contract.getDataRdyTime()));
			mp.put("signdate", sdf.format(contract.getSigndate()));
			mp.put("finishTime", sdf.format(contract.getFinishTime()));
			
			rsls.add(mp);
			
		}

		Map rs = new HashMap();

		rs.put("items", rsls);
		if (list != null) {
			rs.put("success", true);
		} else {
			rs.put("success", false);
		}
		rs.put("totalcount", count);
		rtn(rs, request, response);
		return;
	}

	public void findById(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
		if (id != null && id.length() > 0) {
			ContractService contractService = (ContractService) this.getApplicationContext().getBean(
					"contractService");
			Contract contract = contractService.findById(id);
			if (contract != null) {
				List list = new ArrayList();
				list.add(contract);

				Map rs = new HashMap();
				rs.put("items", list);
				rs.put("success", true);
				rtn(rs, request, response);
				return;
			}

		}

		Map rs = new HashMap();
		rs.put("success", false);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 根据协议的状态，获取协议列表
	 * 
	 * @param request
	 * @param response
	 */
	public void contractByStatus(HttpServletRequest request, HttpServletResponse response) {
		String status = request.getParameter("status");
		String limit = request.getParameter("limit");
		String start = request.getParameter("start");
		if (limit == null || limit.length() > 0) {
			limit = "10";
		}
		if (start == null || start.length() > 0) {
			start = "1";
		}
		List<Contract> list = null;
		Integer count = 0;// 总记录数量
		ContractService contractService = (ContractService) this.getApplicationContext().getBean("contractService");
		if (status != null && status.length() > 0) {
			// 获得当前登录用户的权限列表
			List<Permissions> curplist = (List<Permissions>) request.getSession().getAttribute(
					"CURRENT_PERMISSIONS");
			// 是否有协议管理者的读权限
			List<Permissions> rp = SystermUtil.usrPermissionsList("contractmgr", "read", curplist);
			if (rp.size() > 0) {
				Map map = contractService.selectByContractStatus(Integer.parseInt(status), Integer.parseInt(start),
						Integer.parseInt(limit));
				list = (List<Contract>) map.get("list");
				count = (Integer) map.get("totalcount");
			}
		}
		Map rs = new HashMap();
		rs.put("items", list);
		if (list != null) {
			rs.put("success", true);
		} else {
			rs.put("success", false);
		}
		rs.put("totalcount", count);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 根据协议号，查找属于该协议的未分配的子项列表
	 * 
	 * @param request
	 * @param response
	 */
	public void itemsfree(HttpServletRequest request, HttpServletResponse response) {
		ItemService itemService = (ItemService) this.getApplicationContext().getBean("itemService");
		String contractid = request.getParameter("contractid");
		List<Item> list = itemService.findFreeItemByContractid(contractid);
		Map rs = new HashMap();
		rs.put("items", list);
		rs.put("success", true);
		rtn(rs, request, response);
		return;

	}

	/**
	 * 根据协议号，查找属于该协议的子项列表
	 * 
	 * @param request
	 * @param response
	 */
	public void itemsall(HttpServletRequest request, HttpServletResponse response) {
		ItemService itemService = (ItemService) this.getApplicationContext().getBean("itemService");
		String contractid = request.getParameter("contractid");
		List<Item> list = itemService.findByContractid(contractid);
		Map rs = new HashMap();
		rs.put("items", list);
		rs.put("success", true);
		rtn(rs, request, response);
		return;

	}

	/**
	 * 根据协议单ID查找属于该协议单的Task列表
	 * 
	 * @param request
	 * @param response
	 */
	public void taskall(HttpServletRequest request, HttpServletResponse response) {
		String contractid = request.getParameter("id");
		if (contractid != null && contractid.length() > 0) {
			TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
			List<Task> list = taskService.findByContractid(contractid);

			Map rs = new HashMap();
			rs.put("items", list);
			rs.put("success", true);
			rtn(rs, request, response);
			return;
		} else {

			Map rs = new HashMap();
			rs.put("success", false);
			rtn(rs, request, response);
			return;
		}

	}
}
